console.log('tax injected');
/*
* 厦门全是季报
* */

import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';

let baseInfo;

window.onload = function () {
  // 登录填写账号密码
  if (/\/tlogin\/index.do/g.test(window.location.pathname)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }

  // 财务报表新
  if (/\/wssb\/wssb\/layout\/center.jsp/g.test(window.location.pathname)) {
    // 进入报税页面
    let bjWindow = $('#workspace');
    bjWindow.on('load', function () {
      let taxType = getTaxType(bjWindow[0].contentWindow);
      let period = getReportingCycle(bjWindow[0].contentWindow);
      sendFilter(period, taxType);
    });
  }
  // 财务报表
  if (/\/wssb\/wssb\/public\/jsp\/wssb.jsp/g.test(window.location.pathname)) {
    // 进入报税页面
    let bjWindow = $('#workspace');
    bjWindow.on('load', function () {
      let taxType = getTaxType(bjWindow[0].contentWindow);
      let period = getReportingCycle(bjWindow[0].contentWindow);
      sendFilter(period, taxType);
    });
  }
};

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    data = data.data;
    let sheet = data.saasData.sheet;
    if (sheet == 'sds' || sheet == 'zzs') {
      fillInput(data, sheet);
    } else {
      fillInput(await transformDataByOpenWeb(data));
    }
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfo = data.data;
    autoInputAccount(baseInfo);
  }
}, false);
/**
 * 获取公司信息
 */
function getNationData() {
  let bjWindow = $('#workspace')[0].contentWindow;

  let gsInstitution = getGsInstitution(bjWindow);
  let taxInfo = {
    institution: gsInstitution, // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: ''// 税款所属期止
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  $('#loginId').val(companyInfo.nationalTaxAccount).trigger('blur');
  $('#qyPassword').val(companyInfo.nationalTaxPass);
  $('#userPassword').val(companyInfo.nationalTaxPass);
  $('#qyPassword').blur(function () {
    let $this = $(this);
    $('#userPassword').val($this.val());
  });
}

function fillInput({ saasData }) {
  let sheet = saasData.sheet;
  let bjWindow = $('#workspace')[0].contentWindow;
  let message = '填报成功';
  try {
    let inputData = saasData.data;
    let errorMsg = '';
    if (sheet == 'sds' || sheet == 'zzs') {
      inputData = delSdsData(inputData.openParams.inputData.data.profit);
    }
    for (let key in inputData) {
      if (bjWindow.$(`input[name='${key}']`).length === 0) {
        errorMsg += `${key}字段找不到\n`;
      } else {
        bjWindow.$(`input[name='${key}']`).val((inputData[key] * 1).toFixed(2));
        bjWindow.$(`input[name='${key}']`).change();
      }
    }
    console.error(errorMsg);
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message
    }
  }, '*');
}

function delSdsData(tableData) {
  let sdsData = {};
  sdsData.yysr = tableData.BNLJJE_1;
  sdsData.yycb = tableData.BNLJJE_2;
  sdsData.lrze = tableData.BNLJJE_30;
  return sdsData;
}

function getTaxType(bjWindow) {
  let stromgArr = bjWindow.$('strong');
  let title = stromgArr.eq(2).text(),
    taxType = null;


  if (title.search('资产负债表') != -1) {
    taxType = 'balance';
  } else if (title.search('利润表') != -1) {
    taxType = 'profit';
  } else if (title.search('现金流量表') != -1) {
    taxType = 'cash';
  } else {
    taxType = 'balance';
  }

  return taxType;
}

/**
 * 获取国税会计类型
 */
function getGsInstitution(bjWindow) {
  let text = bjWindow.$('strong').eq(0).text();
  let gsInstitution = 2013; // 国税制度，默认为小企业会计
  text = text.trim();
  if (text.search('适用执行企业会计准则') != -1) {
    gsInstitution = 2007;
  } else if (text.search('适用执行小企业会计准则') != -1) {
    gsInstitution = 2013;
  }
  return gsInstitution;
}

/**
 * @param timeStr 时间字符串 2017-04-01~2017-06-30
 * 获取申报周期并且填充数据
 */
function getReportingCycle(bjWindow) {
  let $table = bjWindow.$('table table table');
  let gsInstitution = getGsInstitution(bjWindow);
  if (gsInstitution == 'gener') {
    $table = $table.eq(1);
  }
  let text = $table.find('tbody tr').eq(1).find('td').eq(0)
    .text();


  let sssq_q = text.substring(5, 11);
  let sssq_z = text.substring(16, 22);

  return {
    sssq_q: sssq_q,
    sssq_z: sssq_z
  };
}

function sendFilter(period, taxType) {
  let sssq_q = period.sssq_q,
    sssq_z = period.sssq_z;

  if (sssq_q && sssq_z) {
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: taxType,
        startTime: sssq_q.replace(/(\d{4})/g, '$1-'),
        endTime: sssq_z.replace(/(\d{4})/g, '$1-')
      }
    }, '*');
  } else if (taxType) {
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: taxType
      }
    }, '*');
  }
}
